/**
 * @author jouyang
 */
if(typeof(QSAPI)=="undefined") var QSAPI={};
if(typeof(QSAPI.Widget)=="undefined") QSAPI.Widget = {};
if(typeof(QSAPI.Widget.Chart)=="undefined") QSAPI.Widget.Chart = {};
QSAPI.Widget.Chart.UIPanel = function(container,chart,config){
	this.chartId = chart.id;
	this.el = container;
	this.relatedSecUrl = "//quote.morningstar.com/stock/competitorRawList.ashx?out=1";
	this.config = config||{}; // some conguration for chart UI
	this.UIcfg={   // control the URl
		showReset:false,
		showExportData:true,
		maxRange:10,
		rangeArray:[]
    };
	// UI Components
	this.uiComponents = {
	};
	// UI elements
	this._elements = {
	};
	this.toolModules = {compare:{txt:QS_Lang.Chart.compare,val:"compare",items:{
			relatedSec:true,autoBox:true,select:true
		}},		
		indicators:{txt:QS_Lang.Chart.indicators,val:"indicators",items:{
			events:true,indicator:true,fundamental:true
		}},
		fundamental:{
			txt:QS_Lang.Chart.fundamental,val:"fundamental"
			
		},
		drawing:{txt:QS_Lang.Chart.drawing,val:"drawing"},
		display:{txt:QS_Lang.Chart.display,val:"display",items:{
			chartCursor:true,chartType:true,yAxisType:true,scaleType:true,selectionMode:true
		}},
		range:{val: "range",items:{  // not need tab
			dateInputs: true,
			frequency: true,
			zoom: true
		}},
		foot: {
			val: "foot",
			items: { // not need tab
				"share": true,
				"export": true
			}
		}          
	};
	this.chartComponent = chart;
	this._init();
};
QSAPI.Widget.Chart.UIPanel.prototype = {
	_init:function(){
        var self = this;
        this._createUI();	
		this._bindEvent(); 
		this._setAfterCallbacks();
		this._initAutoComplete();
		//this._getRelatedSec();
	},
	// initialize the configuation of tool moudule
	 _initUiModules:function(hideBlocks){  // display|chartCursor-chartTyp,drawing,fundamental
        if(typeof(hideBlocks)=="string"&&hideBlocks!=""){
            var modules = hideBlocks.split(","), t, items;
            for(var i=0;i<modules.length;i++){
                t = modules[i].split("|");
                if(!this.toolModules[t[0]]) continue;
                if(t[1]!=null){
                    items = t[1].split("-");
                    for(var j=0;j<items.length;j++){
                        if(!this.toolModules[t[0]]["items"]||!this.toolModules[t[0]]["items"][items[j]]) continue;
                        delete this.toolModules[t[0]]["items"][items[j]]; // delete one block of the tab.
                    }
                }else{ // remove a tab.
                    delete this.toolModules[t[0]];
                }
            }
        }
    },
	// creat the UI elements for exch panel.
	_createPanelUI:function(ky){ //ky: the key of panel.
		var elm = this._elements,items, tabs = this.toolModules,self = this;
		if(ky=="display"){  // create display panel UI
			var isAddYaxisCon = false,yaxisBlockElm;
			var con = $('<div class="qs-gd"><div class="bd"><div class="qs-c"></div></div></div>').appendTo(elm["displayPanel"]).find(".qs-c");
			items = tabs[ky].items ; 
			for(var o in items){
				if(items[o]){ // 
					if(o=="chartCursor"){ // add cursor type block.
						con.append('<div class="qs-urlchart-type-lst qs_urlchart-'+o.toLowerCase()+'"><div class="text"><h4>'+QS_Lang.Chart.chartcursor+'</h4></div><div class="qs-urlchart-cursor-con"></div></div>');
						var cursorList = this.chartComponent.cursorTypeListData;
				        var str="";
				        for(var i=0;i<cursorList.length;i++){
							str+='<a class="qs-urlchart-item" href="javascript:void(0);" data-ckey = "chartCursor" value="'+cursorList[i].val+'">'+cursorList[i].txt+'</a>';
				        }
						elm["chartCursor"]= con.find(".qs-urlchart-cursor-con").html(str);	
					}else if(o=="chartType"){   // add chart type block
						con.append('<div class="qs-urlchart-type-lst qs_urlchart-'+o.toLowerCase()+'"><div class="text"><h4>'+QS_Lang.Chart.charttype+'</h4></div><div class="qs-urlchart-type-con"></div></div>');
						var typeList = this.chartComponent.chartTypeListData;
				        var str="";
				        for(var i=0;i<typeList.length;i++){
							str+='<a class="qs-urlchart-item" href="javascript:void(0);" data-ckey = "chartType" value="'+typeList[i].val+'">'+typeList[i].txt+'</a>';
				        }
						elm["chartType"] = con.find(".qs-urlchart-type-con").html(str);	
					}else if(o=="yAxisType"||o=="scaleType"||o=="selectionMode"){
						if(!isAddYaxisCon){
							yaxisBlockElm = $('<div class="qs-urlchart-type-lst qs_urlchart-'+o.toLowerCase()+'"></div>').appendTo(con);
							isAddYaxisCon = true;
						}
						if(o=="yAxisType"){
							var str="";
							str+='<div class="text"><h4>'+QS_Lang.Chart.yaxis+'</h4></div><div class="qs-urlchart-yAxisType-con"></div>';
							var yCon = $(str).appendTo(yaxisBlockElm).eq(1);
							this.uiComponents["yAxisRatio"] = new Util.ButtonGroup(yCon,this.chartComponent.yaxisAlignListData,{
								onClick:function(v){
									self.chartComponent.setYaxisAlign(v);
									if(self.autoSave)self._autoSave();
								}
							},{inverse:false});
						}else if(o=="scaleType"){
							var str="", cls = items["yAxisType"]?"qs-urlchart-top10":"";
							str+='<div class="text '+cls+'"><h4>'+QS_Lang.Chart.verticalscale+'</h4></div><div class="qs-urlchart-scaleType-con"></div>';
							var scalCon = $(str).appendTo(yaxisBlockElm).eq(1);
							this.uiComponents["scaleRatio"] = new Util.ButtonGroup(scalCon,this.chartComponent.scaleTypeListData,{
								onClick:function(v){	
									self.chartComponent.switchScaleType(v);
									if(self.autoSave)self._autoSave();
								}
							},{inverse:false});
						}else if(o=="selectionMode"){
							if(this.chartComponent.UIConfig.ZoomIn){  //pan,zoom in and zoom out functions.
								this.chartComponent.selectionModeListData.splice(2,1);// remove the zoom out.
								this.chartComponent.selectionModeListData[0].checked = true;
								var str="", cls = items["yAxisType"]?"qs-urlchart-top10":"";
								str+='<div class="text '+cls+'"><h4>'+QS_Lang.Chart.selectionmode+'</h4></div><div class="qs-urlchart-selection-con"></div>';
								var selectCon = $(str).appendTo(yaxisBlockElm).eq(1);
								this.uiComponents["selectionRatio"] = new Util.ButtonGroup(selectCon,this.chartComponent.selectionModeListData,{
									onClick:function(v){	
										self.chartComponent.setSelectionMode(v);
										if(self.autoSave)self._autoSave();
									}
								},{inverse:false});
								selectCon.append('<a href="javascript:void(0)" class="qs-urlchart-zoomout">'+QS_Lang.Chart.reset+'</a>');
							}
						}
					}
				}
			}
		}else if(ky == "indicators"){
			var con = $('<div class="qs-gd"><div class="bd"><div class="qs-c"></div></div></div>').appendTo(elm["indicatorsPanel"]).find(".qs-c");
			items = tabs[ky].items;
			for(var o in items){
				if (items[o]) { // 
					if(o=="indicator"){
						con.append('<div class="qs-urlchart-type-lst qs_urlchart-'+o.toLowerCase()+'"><div class="text"><h4>'+QS_Lang.Chart.indicators+'</h4></div><div class="qs-urlchart-indicators-con"></div></div>');
						var indicatorList = this.chartComponent.indicatorUI;
				        var str="";
				        for(var o in indicatorList){
							var txt = indicatorList[o].title;
							if(o=="MACD")txt = QS_Lang.Chart.macd_name;
		                    str+='<a class="qs-urlchart-item qs-urlchart-indicator-'+o.toLowerCase()+'" href="javascript:void(0);" data-ckey="indicator" value="'+o+'">'+txt+'</a>';
		                }
						con.find(".qs-urlchart-indicators-con").html(str);
						elm["indicatorInputPanel"]= $('<div class="qs-urlchart-type-lst"><div class="text"><h4></h4></div><div class="qs-urlchart-indicatorInput-con"></div></div>').appendTo(con);
						var str='<div class="para-list"></div><div class="action-row"><a  href="javascript:void(0);" class = "qs-ui-btn add" value="draw">'+QS_Lang.Chart.add+'</a>';
						str+='<a href="javascript:void(0);" class = "qs-ui-btn canel" value="cancel">'+QS_Lang.Chart.cancel+'</a>';
						str+='<a href="javascript:void(0);" class = "qs-ui-btn remove" value="remove">'+QS_Lang.Chart.remove+'</a></div>';
						elm["indicatorInputPanel"].find(".qs-urlchart-indicatorInput-con").html(str);
						elm["indicatorInputPanel"].hide();
					}else if(o=="events"){
						con.append('<div class="qs-urlchart-type-lst  qs_urlchart-'+o.toLowerCase()+'"><div class="text"><h4>'+QS_Lang.Chart.events+'</h4></div><div class="qs-urlchart-events-con"></div></div>');
						var eventList = this.chartComponent.eventsData, str="";
		                for(var i=0;i<eventList.length;i++){
		                    str+='<a class="qs-urlchart-item" href="javascript:void(0);" data-ckey="events" value="'+eventList[i].val+'">'+eventList[i].txt+'</a>';
		                }
		                elm["events"]= con.find(".qs-urlchart-events-con").html(str);
					}
				}
			}
			
		}else if(ky=="fundamental"){
			var con = $('<div class="qs-gd"><div class="bd"><div class="qs-c"></div></div></div>').appendTo(elm["fundamentalPanel"]).find(".qs-c");
			con.append('<div class="qs-urlchart-type-lst qs_urlchart-'+ky.toLowerCase()+'""><div class="text"><h4>'+QS_Lang.Chart.fundamental+'</h4></div><div class="qs-urlchart-fundamental-con"></div></div>');
			var vaList = this.chartComponent.valuations;
	        var str="";
	        for(var o in vaList){
                str+='<a class="qs-urlchart-item" href="javascript:void(0);" data-ckey="indicator" value="'+o+'">'+vaList[o].name+'</a>';
            }
			con.find(".qs-urlchart-fundamental-con").html(str);
		}else if(ky=="drawing"){
			var con = $('<div class="qs-gd"><div class="bd"><div class="qs-c"></div></div></div>').appendTo(elm["drawingPanel"]).find(".qs-c");
			con.append('<div class="qs-urlchart-type-lst qs_urlchart-'+ky.toLowerCase()+'"><div class="text"><h4>'+QS_Lang.Chart.drawing+'</h4></div><div class="qs-urlchart-drawing-con"></div></div>');
			var dList = this.chartComponent.drawingData;
	        var str="";
	        for(var i=0;i<dList.length;i++){
				if(dList[i].val=="note") continue;
                str+='<a class="qs-urlchart-item" href="javascript:void(0);" data-ckey="drawing" value="'+dList[i].val+'">'+dList[i].txt+'</a>';
            }
			con.find(".qs-urlchart-drawing-con").html(str);
		}else if(ky == "compare"){
			var con = $('<div class="qs-gd"><div class="bd"><div class="qs-c"></div></div></div>').appendTo(elm["comparePanel"]).find(".qs-c");
			items = tabs[ky].items;
			for(var o in items){
				if (items[o]) { // 
					if(o=="relatedSec"){
						con.append('<div class="qs-urlchart-type-lst qs_urlchart-'+o.toLowerCase()+'"><div class="text"><h4>'+QS_Lang.Chart.relatedsecurities+'</h4></div><div class="qs-urlchart-relatedSec-con"></div></div>');
						elm["relatedSec"] = con.find(".qs-urlchart-relatedSec-con");
					}else if(o=="autoBox"){
						var str= '<div class="qs-urlchart-type-lst qs-urlchart-auto-lst"><div class="text"><h4>';
						str+=QS_Lang.Chart.enter+' '+QS_Lang.Chart.tickers+'</h4></div><div class="qs-urlchart-tickers-con">';
						str+='<input class="qs-ui-ipt" id='+this.chartId+'_autoBox /><a class="qs-ui-btn go" value="auto" href="javascript:void(0)">'+QS_Lang.Chart.add+'</a></div>';
						str+='<div class="text qs-benchmark qs-urlchart-top10"><h4>'+QS_Lang.Chart.enter+' '+QS_Lang.Chart.benchmarks+'</h4></div>';
                        str+='<div class="qs-urlchart-benchmark-con qs-benchmark"><input class="qs-ui-ipt" id='+this.chartId+'_benchmarkBox /><a class="qs-ui-btn go" href="javascript:void(0)" value="benchmark">'+QS_Lang.Chart.add+'</a></div></div>';
						con.append(str);
                        elm["autoBox"]= con.find(".qs-urlchart-auto-lst");
					}else if(o=="select"){
						var str='<div class="qs-urlchart-type-lst qs-urlchart-select-lst"><div class="text"><h4>'+QS_Lang.Chart.recentsecurities+'</h4></div>';
                        str+='<ul class="qs-urlchart-select-ticker" ></ul></div>';
						con.append(str);
						elm["select"] = con.find("ul.qs-urlchart-select-ticker");
					}
				}
			}
		}
	},
	_showIndicatorParaPanel:function(value){
		var elm = this._elements,indicatorList = this.chartComponent.indicatorUI;
		if(elm["indicatorInputPanel"]!=null){
			elm["indicatorInputPanel"].find(".text H4").html(indicatorList[value].title);
			elm["indicatorInputPanel"].attr("value",value);
			var str = "",idr = indicatorList[value];
            for (var i = 0; i < idr.parameter.length; i++) {
                str += '<div class="row"><div class="row-left"><span>' + idr.parameter[i] + '</span></div><input type="text" class="qs-ui-ipt"  value="' + (typeof(idr.defaultValue[i]) == "undefined" ? "" : idr.defaultValue[i]) + '" ></div>';
            }
			elm["indicatorInputPanel"].find(".para-list").html(str);
			elm["indicatorInputPanel"].show();
			
		}
	},
	_changeRangeUI: function(range){
        this._elements.zoom.find("a").removeClass("on");
        this._elements.zoom.find("a[value=" + range + "]").addClass("on");
    },
	// bind events to UI elements.
	_bindEvent:function(){  // bind the events to elements
	 	var self = this, elm = this._elements;
		this.el.find(".qs-uchart-tab .tabs").unbind("click").bind("click",function(e){
			var el = $(e.target);
			var ky = el.attr("value");
			if(el.hasClass("tabon")){
				el.removeClass("tabon");
				$(".qs-urlchart-"+ky).hide();
                if(self.isTabConOpen){ 
                    self.isTabConOpen = false;
                }       
			}else{
				$(".qs-uchart-tab .tabs .tabon").removeClass("tabon");
				el.addClass("tabon");
				$(".qs-urlchart-panel").hide();
				$(".qs-urlchart-"+ky).show();
                if(!self.isTabConOpen){ // show tab panel
                    self.isTabConOpen = true;
					self.panelHeight = $(".qs-urlchart-"+ky).height();
                }   
			}
		});
		if(elm["zoom"]!=null){
            elm["zoom"].unbind("click").bind("click.webpage",function(e){
                var t = $(e.target);
                var range = t.attr("value");
				if(range=="reset"){  // click the reset button
					//GB_ChartDataManager.quoteDataMap={};  // clear the cached data.
					//GB_ChartDataManager.registeredSymbols={};
					//var dHeight = self.el.find(".rtc-price-chart").height()+30;// 30 px is the minichart.
					//if(self.chartComponent.showVolume){
					//	dHeight+=80;
					//}
					//self.isTabConOpen = false;
					//self._elements = {};// clear the elements cache
					//self._init();
				}else if(range=="export"){  // export data to excel
					self.chartComponent.exportDataToExcel();
				}else{
					self.chartComponent.changeRange(range);
					self._changeRangeUI(range);
				}
            });
        }
		if(elm.displayPanel != null){
			elm.displayPanel.find(".qs-urlchart-item").unbind("click").bind("click",function(e){
				var o = $(this);
	            var type = o.data("ckey"), value = o.attr("value");
	            if (type == "chartCursor") {
	                self.chartComponent.setCursorType(value);
	            } else if (type == "chartType") {
	                self.chartComponent.setChartType(value);
	            }
	            o.parent().find("a").removeClass("qs-urlchart-item-on");
	            o.addClass("qs-urlchart-item-on");
				if(self.autoSave)self._autoSave();
			});
			elm.displayPanel.find(".qs-urlchart-zoomout").unbind("click").bind("click",function(e){
				self.chartComponent.resetZoom();
			});
		}
		if(elm.indicatorsPanel != null){
			elm.indicatorsPanel.find(".qs-urlchart-item").unbind("click").bind("click",function(e){
				var o = $(this);
	            var type = o.data("ckey"), value = o.attr("value");
	            if (type == "events") {
					if (o.hasClass("qs-urlchart-item-on")) {
			            self.chartComponent.switchEvents(value, false);
			            o.removeClass("qs-urlchart-item-on")
			        } else {
			            self.chartComponent.switchEvents(value, true);
			            o.addClass("qs-urlchart-item-on");
			        }
					if(self.autoSave)self._autoSave();
	            } else if (type == "indicator") {
	                var d = self.chartComponent.indicatorUI;
					if(d[value]&&d[value].parameter&&d[value].parameter.length){// need input parameters.
						elm.indicatorsPanel.find("a.qs-urlchart-item").removeClass("qs-urlchart-item-clicked");
						o.addClass("qs-urlchart-item-clicked");
						self._showIndicatorParaPanel(value);
					}else{
						if(o.hasClass("qs-urlchart-item-on")){
							self.chartComponent.removeIndicators(value);
							o.removeClass("qs-urlchart-item-on");
						}else{
							self.chartComponent.addIndicators(value);
							o.addClass("qs-urlchart-item-on");
							if(value=="Volume"){
								elm.indicatorsPanel.find("a[value='VPlus']").removeClass("qs-urlchart-item-on");
							}else if(value=="VPlus"){
								elm.indicatorsPanel.find("a[value='Volume']").removeClass("qs-urlchart-item-on");
							}
						}
						
					}
	            }
			})
		}
		if(elm.fundamentalPanel != null){  // fundamental chart.
			elm.fundamentalPanel.find(".qs-urlchart-item").unbind("click").bind("click",function(e){
				var o = $(this);
				var value = o.attr("value");
				if(o.hasClass("qs-urlchart-item-on")){
					o.removeClass("qs-urlchart-item-on");
					self.chartComponent.removeValuations(value);
				}else{
					o.addClass("qs-urlchart-item-on");
					self.chartComponent.addValuations(value);
				}
			});
		}
		if(elm["drawingPanel"]!=null){
			elm.drawingPanel.find(".qs-urlchart-item").unbind("click").bind("click",function(e){
				var o = $(this);
				var value = o.attr("value");
				if(o.hasClass("qs-urlchart-item-on")){
					self.chartComponent.cancelDrawing(value);
					o.removeClass("qs-urlchart-item-on");
				}else{
					self.chartComponent.beginDrawing(value);
					elm.drawingPanel.find(".qs-urlchart-item-on").removeClass("qs-urlchart-item-on");
					o.addClass("qs-urlchart-item-on");
				}
			});
		}
		if(elm["indicatorInputPanel"]!=null){
			elm["indicatorInputPanel"].find(".action-row a").unbind("click").bind("click",function(e){
				var v = $(e.target).attr("value");
				var indicatorKey = elm["indicatorInputPanel"].attr("value");
				if(v=="draw"){ // add a indicator.
					var ipts = elm["indicatorInputPanel"].find(".para-list input"), args = [];
					args[0] = indicatorKey;
	                for (var i = 0; i < ipts.length; i++) {
	                    args.push(ipts[i].value);
	                }
                	self.chartComponent.addIndicators.apply(self.chartComponent, args);
					elm.indicatorsPanel.find("a[value='"+indicatorKey+"']").removeClass("qs-urlchart-item-clicked");
				}else if(v=="remove"){ // remove a indicator
					if (indicatorKey != null) {
	                    self.chartComponent.removeIndicators(indicatorKey);
	                	elm["indicatorInputPanel"].hide();
	                }
					elm.indicatorsPanel.find("a[value='"+indicatorKey+"']").removeClass("qs-urlchart-item-clicked");
				}else if(v=="cancel"){  // cancel the indicator.
					elm.indicatorsPanel.find("a[value='"+indicatorKey+"']").removeClass("qs-urlchart-item-clicked");
					indicatorKey = null;
				}
				elm["indicatorInputPanel"].hide();
			});
		}
		if(elm["select"]!=null){
			elm["select"].unbind("click").bind("click",function(e){
				var o = $(e.target);
				if(o.hasClass("close")){ // click the close button.
					var value = o.attr("value");
					o.parent().remove();
					QSAPI.TickerFactory.create([value],{onSuccess:function(tickers){
						self.chartComponent.removeCompairTicker(tickers[0]);
					}});
					//self.chartComponent.removeCompairTicker(value);
				}
			})
		}
		if (self._elements["frquency"] != null) { // need display frequency ddl.
			self.uiComponents.ddlFrequency = new Util.DropDownList(self._elements["frquency"][0], function(k, v){
				self.chartComponent.setFrequency(v);
				if(self.autoSave)self._autoSave();
			}, self.chartComponent.frequencyListData, {
				triggerByClick: false,
				width: 76,
				disable: false,
				actionAtInit: false
			});
		}
        if(elm["shareChart"]!=null){
            elm["shareChart"].find("a").unbind("click").bind("click",function(e){
            var o = $(e.target);
            if(o.hasClass("qs-urlchart-share")){
                var s = elm["shareChart"].find("span.qs-urlchart-share-ico");
                var sInput = elm["shareChart"].find(".qs-urlchart-share-ipt");
                if(s.hasClass("qs-urlchart-share-ico-on")){
                    s.removeClass("qs-urlchart-share-ico-on");
                    sInput.hide();
                }else{
                    s.addClass("qs-urlchart-share-ico-on");
                    var sObj = self._getChartProfile(); 
                    var str = $.toJSON(sObj);
                    var shareUrl = window.location.href+"&statePara="+ encodeURIComponent(str);
                    sInput.val(shareUrl).show();
                }
            }else if(o.hasClass("qs-urlchart-export")){  // export data to excel.
                self.chartComponent.exportDataToExcel();
            }});
        }
	},
	_setAfterCallbacks:function(){  // set after callbacks to chart component
		var self = this, elm = this._elements,scfg = this.statusConfig;
		this.chartComponent.afterRemoveVolumeChart = function(){ // remove volume chart.
			elm["indicatorsPanel"].find("a[value='Volume']").removeClass("qs-urlchart-item-on");
			elm["indicatorsPanel"].find("a[value='VPlus']").removeClass("qs-urlchart-item-on");
			elm["indicatorsPanel"].find("a[value='SMVV']").removeClass("qs-urlchart-item-on");
			if(self.autoSave)self._autoSave();
		}
		this.chartComponent.afterAddIndicators = function(data){
			if(elm["indicatorsPanel"])elm["indicatorsPanel"].find("a[value='"+data.indicatorName+"']").addClass("qs-urlchart-item-on");
			if(self.autoSave)self._autoSave();
		}
		this.chartComponent.afterRemoveIndicators = function(data){
			if(elm["indicatorsPanel"])elm["indicatorsPanel"].find("a[value='"+data.indicatorName+"']").removeClass("qs-urlchart-item-on");
			if(self.autoSave)self._autoSave();
		}
		 this.chartComponent.afterAddValuationCallback = function(data){
			  if(self.autoSave)self._autoSave();
        }
        this.chartComponent.afterRemoveValuationCallback = function(data){
			if(elm["fundamentalPanel"])elm["fundamentalPanel"].find("a[value='"+data.name+"']").removeClass("qs-urlchart-item-on");
			if(self.autoSave)self._autoSave();
        }
		this.chartComponent.datePeriodChanged = function(data){
			if(data.zoomRange==11){  // after customize date.
				if(elm.zoom)elm.zoom.find("a").removeClass("on");
			}
			if(self.autoSave)self._autoSave();
		}
		this.chartComponent.afterAddTickers=function(data){
			if(data&&data.symbol&&data.symbol.length){
				var list = data.symbol,value;
				for(var i=0;i<list.length;i++){
					value = self._getSymbolId(list[i]);//list[i].type==8?list[i].secId:list[i].performanceId;
					if(elm["relatedSec"]!=null){
						elm["relatedSec"].find("a[value='"+value+"']").addClass("qs-urlchart-item-on");
					}
					self._addSelectedItem(list[i].clientTicker,list[i].ticker,value);
				}
			}
			if(self.autoSave)self._autoSave();
		}
		this.chartComponent.afterRemoveTickers=function(data){
			var value = self._getSymbolId(data.symbol);//data.symbol.type==8?data.symbol.secId:data.symbol.performanceId;
			if(elm["relatedSec"]!=null){
				elm["relatedSec"].find("a[value='"+value+"']").removeClass("qs-urlchart-item-on");
			}
            if(elm["select"]!=null){
                elm["select"].find("a[value='"+value+"']").parent().remove();
            }
			if(self.autoSave)self._autoSave();
		};
        this.chartComponent.afterSwitchIIV = function(data){  // when click the iiv in chart legend.
            if(elm["iiv"]!=null&&self.uiComponents["iivChk"]){
                if (data.showIIVTicker) {
                    self.uiComponents["iivChk"].btns["showIIV"].select();
                }else {
                    self.uiComponents["iivChk"].btns["showIIV"].inverse()
                }
            }
        };
		this.chartComponent.afterSwitchMainTickerFromCompareTickers=function(mTInfos,cT){  // mT: old mainTicker;
			if(elm["select"]!=null){
				var value = self._getSymbolId(mTInfos)
                elm["select"].find("a[value='"+cT+"']").parent().remove();
				self._addSelectedItem(mTInfos.clientTicker,mTInfos.ticker,value)
            }
		};
		this.chartComponent.afterAcceptTickers = function(data){
            self._addIIVOption();
            var t = data.mainTicker;
			self.type = t.mType=="Options"?2:t.mType=="FO"?8:1;
            //if(t) self.statusConfig.mTicker = self.defaultConfig.mTicker = self.chartComponent.mainTicker; 
            if(t.mType=="FE"){  // remove the fundamental tab
                delete self.toolModules["fundamental"];
                if(self._elements["toolTabs"]!=null)self._elements["toolTabs"].find("a[value='fundamental']").parent().hide();
                if(self._elements["fundamentalPanel"]!=null)self._elements["fundamentalPanel"].hide();
            }else{
				if(self._elements["toolTabs"]!=null)self._elements["toolTabs"].find("a[value='fundamental']").parent().show();
                if(self._elements["fundamentalPanel"]!=null){
					self.toolModules["fundamental"] = {txt:QS_Lang.Chart.fundamental,val:"fundamental"};
					//self._elements["fundamentalPanel"].show();
				}
			}
			if(self.toolModules["compare"]&&self.toolModules["compare"].items["relatedSec"]){
				self._getRelatedSec(self._getSymbolId(t));
			}
        };
		this.chartComponent.selectedDatesChanged = function(s,e){
			if(self.uiComponents.customDateB)self.uiComponents.customDateB.setDate(s,e);
		};
		this.chartComponent.afterDrawEnd = function(drawType){ 
			if (elm.drawingPanel!= null) {
				elm.drawingPanel.find("[value='" + drawType + "']").removeClass("qs-urlchart-item-on");
			}
		};
		this.chartComponent.afterFrequencyDataChanged = function(data){ // frequency list has changed.
			self.uiComponents.ddlFrequency.rebindData(data);
		};
		this.chartComponent.afterFrequencyChanged = function(frequnecy){
			self.uiComponents.ddlFrequency.setTextValue("",frequnecy);
		};
		this.chartComponent.afterLoadConfig = function(cfg){
			self._initUiComponentsStatus(cfg);
		}
	},
	_createUI:function(){  // create the control panel.		
	    var exStr = "";
	    if(this.config&&this.config.autoCompleteBox){
            exStr = '<div class="qs-urlchart-gbbox-con"><input class="qs-ui-ipt" id="'+this.chartId+'gb_box" />'+'<a class="qs-ui-btn go" value="gb_auto" href="javascript:void(0)">'+QS_Lang.Chart.go+'</a></div>';
        }		
		var str='<div class="qs-gd2 qs-urlchart-tab-container">'+
		        '<div class="bd">'+
				'<div class="qs-main"><div class="qs-c"><div class="qs-uchart-tab"><ul class="tabs"></ul></div></div></div>'+
				'<div class="qs-c">'+exStr+'</div>'+
				'</div>'+
		        '</div>';
		
		$(str).appendTo(this.el);
		str="";
        var tabNum=0;
		for(var o in this.toolModules){
            if(o=="range"||o=="foot") continue;
			str+='<li><a href="javascript:void(0);" value="'+this.toolModules[o].val+'">'+this.toolModules[o].txt+'</a></li>';
			// create panel for each tab item.
			this._elements[this.toolModules[o].val+"Panel"] = $('<div class="qs-urlchart-panel qs-urlchart-'+this.toolModules[o].val+'"></div>').appendTo(this.el);
			this._createPanelUI(this.toolModules[o].val);
            tabNum++;
		}
        if(tabNum==0){  // remove the tab container.
            this.el.find(".qs-urlchart-tab-container .qs-main").remove();
			this.el.find(".qs-urlchart-tab-container").hide();
        }
		this._elements.toolTabs = this.el.find("ul.tabs").html(str);  // create tabmenu.
		// create zoom range buttons.
        var rangeRow;
        if(this.toolModules["range"]){
            rangeRow = $('<div class="qs-urlchart-range"></div>').appendTo(this.el);
            var mr = this.toolModules["range"].items;
            if(mr["dateInputs"]){
                this._elements["customDate"] = $('<div class="qs-urlchart-custom-date-con"></div>').appendTo(rangeRow);  // create custom date boxes.
                var self = this;
                this.uiComponents.customDateB = new RTQ_chartCustomDataBox(this._elements.customDate,{
                    startDate:null,
                    endDate:null,
                    width:80,
                    splitLabel:"-",
                    callback:function(s,e){
                        self.chartComponent.changeDatePeriod(s,e);
                    },
                    bindEvent:true
                });
            }
			if(mr["frequency"]){
                this._elements["frquency"]= $('<div class="qs-urlchart-freq-con"></div>').appendTo(rangeRow);
            }
			if(mr["zoom"]){
				rangeRow.append('<div class= "qs-urlchart-zoom-con"></div>');
                var zoomList = this.chartComponent.zoomListData;
                str=this._bindZoomData(zoomList);
                this._elements.zoom = rangeRow.find(".qs-urlchart-zoom-con").html(str);
            }
			
        }
	},
	_bindZoomData:function(zoomList){
		str="";
		for(var i=0;i<zoomList.length;i++){
			if(zoomList[i].val>=11||zoomList[i].val>this.UIcfg.maxRange)continue;  //remove the 2d and 2 month button.
			if(this.UIcfg.rangeArray.length&&$.inArray(parseInt(zoomList[i].val),this.UIcfg.rangeArray)<0) continue;
			str+='<a value="'+zoomList[i].val+'" href="javascript:void(0);" >'+zoomList[i].txt+'</a>';
		}
		if(this.UIcfg.showReset)str+='<a class="reset" value="reset" href="javascript:void(0);">'+QS_Lang.Chart.reset+'</a>';
		if(this.UIcfg.showExportData)str+='<a class="reset" value="export" href="javascript:void(0);">'+QS_Lang.Chart.exportdatatoexcel+'</a>';
		return str;
	},
	// creat the auto-complete boxes
	_initAutoComplete:function(){
		var self = this;
        if (this.toolModules["compare"] && this.toolModules["compare"].items["autoBox"]) {  // create the compare auto-complete box
			this.acbWidget = QSAPI.Widget.AutoComplete($(document.body),{},{},null);
			this.acbWidget.subscribe(this.chartId+'_autoBox',{  // autocomplete box in compare section
				}, {onClick:function(ticker){
					self.chartComponent.addCompairTickers([ticker]);
			}});
			this.el.find(".qs-urlchart-gbbox-con .go").bind("click",function(e){
				self.acbWidget.trigger(this.chartId+'_autoBox');
			})
            if(typeof(this.chartComponent.indexsMap)== "undefined"){  //not include relative indexs.
                if(this._elements["autoBox"]){
                    this._elements["autoBox"].find(".qs-benchmark").remove();
                }
            }else{
                var indexBox = new simpleAutoCompleteBox(this.chartId + "_benchmarkBox", this.chartComponent.indexsMap, "key{txt}", {
                    onclick: function(key){
                        $(self.chartId + "_benchmarkBox").val("");
                        QSAPI.TickerFactory.create([key],{onSuccess:function(tickers){
							self.chartComponent.addCompairTickers(tickers);
						}});
                    }
                }, {
                    width: 180
                });
                indexBox.init();
            }      
        }
		if(this._elements["comparePanel"]!=null){
			this._elements["comparePanel"].find(".qs-urlchart-auto-lst .go").bind("click",function(e){  // click add 
				var t  = $(e.target).attr("value"),value="";
				if(t=="auto"){
                   self.acbWidget.trigger(self.chartId+"_autoBox");
				}else if(t=="benchmark"){
					value = self._elements["comparePanel"].find("#"+self.chartId+"_benchmarkBox").val();
					QSAPI.TickerFactory.create([value],{onSuccess:function(tickers){
						self.chartComponent.addCompairTickers(tickers);
					}});
				}	
			})
		}
		if(this.config&&this.config.autoCompleteBox){
			if(!this.acbWidget)this.acbWidget = QSAPI.Widget.AutoComplete($(document.body),{},{},null);
			this.acbWidget.subscribe(this.chartId+'gb_box',{  // autocomplete box in compare section
				}, {onClick:function(ticker){
					self.chartComponent.acceptTicker(ticker);
			}});
			this.el.find(".qs-urlchart-gbbox-con .go").bind("click",function(e){
				self.acbWidget.trigger(this.chartId+'gb_box');
			})
		}
        
    },
	// 
	_initUiComponentsStatus: function(cfg) {  // initilize the status of UI  components.
	 	var el = this._elements, uiComps = this.uiComponents;
        if(cfg.chartCursor != null&&el["chartCursor"]!=null ) {
            el["chartCursor"].find("a[value='"+cfg.chartCursor+"']").addClass("qs-urlchart-item-on");
        }
		if(cfg.chartStyle != null && el["chartType"] != null) {
            el["chartType"].find("a[value='"+cfg.chartStyle+"']").addClass("qs-urlchart-item-on");
        }
        if(uiComps["yAxisRatio"]!=null){
            if(cfg.yaxisAlign!=null){
                uiComps["yAxisRatio"].btns[cfg.yaxisAlign].select();
            }else{
                uiComps["yAxisRatio"].btns["right"].select();
            }
        }
        if (cfg.zRange != null&&el["zoom"]!=null) {
			el["zoom"].find("a[value='"+cfg.zRange+"']").addClass("on");
		}
        if(uiComps["scaleRatio"]!=null){
            if(cfg.scaleType!=null){
                uiComps["scaleRatio"].btns[cfg.scaleType].select();
            }else{
                uiComps["scaleRatio"].btns["0"].select();
            }
        }	
		if(cfg.events!=null&&el["events"]!=null){
			for(var o in cfg.events){
				if(cfg.events[o]){
					el["events"].find("a[value='"+o+"']").addClass("qs-urlchart-item-on");
				}
			}
		}
		if(cfg.indicatorsData!=null&&el["indicatorsPanel"]!=null){
			for(var o in cfg.indicatorsData){
				if(cfg.indicatorsData[o].show){
					el["indicatorsPanel"].find("a[value='"+o+"']").addClass("qs-urlchart-item-on");
				}
			}
		}
		if(cfg.valuations!=null&&el["fundamentalPanel"]!=null){
			for(var o in cfg.valuations){
				if(cfg.valuations[o].show){
					el["fundamentalPanel"].find("a[value='"+o+"']").addClass("qs-urlchart-item-on");
				}
			}
		}
    },
	_getSymbolId:function(info){
        return info.type==8?info.secId:info.performanceId;
    },
	_addSelectedItem:function(clientTicker,ticker,id){
		var elm = this._elements;
		if(elm["select"]!=null){
			var txt = clientTicker||ticker;
			if(elm["relatedSec"]!=null){
				var d = elm["relatedSec"].find("a[value='"+id+"']");
				if(d.length){
					txt = d.html();
				}
			}
			if(elm["select"].find("a[value='"+id+"']").length==0){
				var str = '<li class="on"><a  href="javascript:void(0);">' + txt + '</a><a class="close" href="javascript:void(0)" value=' + id + '>x</a></li>';
				elm["select"].append(str);
			}
		}
	},
	_getRelatedSec:function(ticker){
        var self = this,str = "";
		if(this.chartComponent.sType=="Options"){
			this._relatedArrived("");
		}else{
			//var ticker = this.chartComponent.mainTicker;
			$.getJSON( this.relatedSecUrl+"&t="+ticker + "&cb=?",function(data){
				self._relatedArrived(data);
			});
		}
	},
	_relatedArrived:function(data){
		var str = "", self = this;
		for (var i = 1; i < data.length; i++) {
			str += '<a  class="qs-urlchart-item" idx="' + i + '" href="javascript:void(0);" value="' + data[i].PID + '">' + data[i].Symbol + '<span>' + data[i].Name + '</span></a>';
		}
		if(str == ""){  // no related securities. remove the block.
			this._elements["relatedSec"].html("").parent().hide();//parent().remove();
		}else{
			this._elements["relatedSec"].html(str).parent().show();
			this._elements["relatedSec"].find(".qs-urlchart-item").unbind("click").bind("click",function(e){
				var o = $(this);
				var  value = o.attr("value"),flag = o.hasClass("qs-urlchart-item-on");
				 QSAPI.TickerFactory.create([value],{onSuccess:function(tickers){
					if (flag) {
						self.chartComponent.removeCompairTicker(tickers[0]);
					}else{
						self.chartComponent.addCompairTickers(tickers);
					}
				}});
				
			});
		}
	},
	_addIIVOption:function(){
		var con = this._elements["comparePanel"]?this._elements["comparePanel"].find(".qs-urlchart-auto-lst"):null;
		var self = this;
		if(con!=null&&con.length&&this.chartComponent&&this.chartComponent.iivTicker!=null&&this.chartComponent.iivTicker!=""){  // has iiv ticker for ETF
			if(!this._elements["iiv"]){
                this._elements["iiv"]= $('<div class="qs-urlchart-iiv-con"></div>').appendTo(con);
                this.uiComponents["iivChk"]= new Util.ButtonGroup(this._elements["iiv"], [{txt:QS_Lang.Chart.inav+"/"+QS_Lang.Chart.nav,val:'showIIV'}], {
                onClick: function(v, btn){
                    if(v=="showIIV"){
                        self.chartComponent.switchIIV(btn.isSelected);
                    }
                }
                },{type:'checkbox',vertical:true});
            }  
		}
	}
}